﻿using System.Collections.Generic;
using System;
using System.IO;
using System.Xml.Serialization;
namespace ProxyViewModel.Samples.TodoList.Model {
	/// <summary>
	/// Simple tasks repository. Serializes tasks to file and desirializes
	/// </summary>
	public class TasksRepository {
		public static readonly string FilePath = "todo.xml";

		public IList<TodoTask> GetTodoList() {
			List<TodoTask> list = new List<TodoTask>();
			if (File.Exists(FilePath)) {
				OpenFile(e => {
					XmlSerializer serializer = new XmlSerializer(typeof(List<TodoTask>));
					list = (List<TodoTask>)serializer.Deserialize(e);
				}, FileMode.Open);
			}
			return list;
		}

		public void Save(List<TodoTask> tasks) {
			OpenFile(e => {
				XmlSerializer serializer = new XmlSerializer(typeof(List<TodoTask>));
				serializer.Serialize(e, tasks);
			}, File.Exists(FilePath) ? FileMode.Truncate : FileMode.OpenOrCreate);
		}

		private void OpenFile(Action<Stream> action, FileMode mode) {
			using (FileStream stream = new FileStream(FilePath, mode, FileAccess.ReadWrite)) {
				action(stream);
			}
		}
	}
}
